/*
 * CRC.h
 *
 * Created: 6/14/2013 2:45:16 AM
 *  Author: Tim
 */ 


#ifndef CRC_H_
#define CRC_H_

#include <avr/io.h>
#include "status.h"

static inline status_t crcCheck( uint8_t *msg, uint16_t numBytes)
{
	uint16_t cnt = 0;
	
	CRC.CTRL = CRC_RESET_RESET1_gc;	//reset the CRC interface
	asm("nop");						//wait one clock to allow the CRC to reset
	
	CRC.CTRL = CRC_SOURCE_IO_gc;	//set the CRC to be used manually
	
	for (cnt = 0; cnt < numBytes-2; cnt++)
	{
		CRC.DATAIN = msg[cnt];
	}
	CRC.STATUS = CRC_BUSY_bm;	//operation finished signal to the CRC module
	
	//checksum1 is the high byte
	//checksum0 is the low byte
	if(CRC.CHECKSUM1 == msg[numBytes-2] && CRC.CHECKSUM0 == msg[numBytes -1])	return OPP_SUCCESSFUL;
	else																		return OPP_FAILED;
}

static inline void crcAppend( uint8_t *msg, uint16_t numBytes)
{
	uint16_t cnt = 0;
	
	CRC.CTRL = CRC_RESET_RESET1_gc;	//reset the CRC interface
	asm("nop");						//wait one clock to allow the CRC to reset
	
	CRC.CTRL = CRC_SOURCE_IO_gc;	//set the CRC to be used manually
	
	//start out with a count of two since the crc is bytes long
	for (cnt = 0; cnt < numBytes-2; cnt++)
	{
		CRC.DATAIN = msg[cnt];
	}
	CRC.STATUS = CRC_BUSY_bm;	//operation finished signal to the CRC module
	
	//checksum1 is the high byte
	msg[numBytes-2] = CRC.CHECKSUM1;
	//checksum0 is the low byte
	msg[numBytes-1] = CRC.CHECKSUM0;
}

#endif /* CRC_H_ */